package com.buddha.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buddha.api.common.Result;
import com.buddha.api.entity.Brand;
import com.buddha.api.service.impl.BrandServiceImpl;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mybatis-plus
 * @since 2023-07-06
 */
@CrossOrigin(origins = {"*"})
@RestController
@RequestMapping("/brand")
public class BrandController {

    @Resource
    BrandServiceImpl brandService;

    /**
     * 添加品牌
     * @param brand
     * @return
     */
    @PostMapping("/add")
    public Result addBrand(@RequestBody Brand brand){
        //Brand idBrand = brandService.getById(brand.getBrandId());
        if(brand.getBrandId() == null){
            // 添加
            brand.setBrandTemp(0);
            QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("brand_name",brand.getBrandName());
            boolean flag = brandService.getOne(queryWrapper)!=null;
            if(flag) return Result.error("300","该品牌名已添加");
            flag = brandService.save(brand);
            return flag? Result.success():Result.error("300","添加出错");
        }else {
            // 更新数据
            boolean flag = brandService.updateById(brand);
            return flag?Result.success():Result.error();
        }
    }


    //分页信息分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String brandName){
        //pageNum为起始下标
        IPage<Brand> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        //添加模糊查询条件
        queryWrapper.like("brand_name",brandName);
        IPage<Brand> medicalPage = brandService.page(page, queryWrapper);
        return Result.success(medicalPage);
    }

    // 删除
    @PostMapping("/del")
    public Result delBrand(@RequestBody String brandId){
        boolean flag = brandService.removeById(brandId);
        return flag?Result.success():Result.error();
    }

    // 加载全部品牌信息
    @GetMapping("/all")
    public Result getAllBrands(){
        List<Brand> brandList = brandService.list();
        return Result.success(brandList);
    }

    @GetMapping("/id")
    public Result getById(@RequestParam Integer id){
        QueryWrapper<Brand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brand_id",id);
        //queryWrapper.last("LIMIT 3");
        Brand brand = brandService.getOne(queryWrapper);
        return Result.success(brand);
    }
}
